<?php



class LoginController extends Zend_Controller_Action
{
	private $logger;
	private $bootstrap;

	public function init()
	{
		$this->logger = new Zend_Log();
		$writer = new Zend_Log_Writer_Stream(APPLICATION_PATH . '/debug.log');
		$this->logger->addWriter($writer);
		$this->bootstrap = $this->getInvokeArg('bootstrap');
		//$this->logger->log(print_r($this, true), Zend_Log::ALERT);
	}



	public function getForm()
	{
		$form = new Zend_Form();
		$form->setMethod("POST");
		$base_url = $this->getFrontController()->getBaseUrl();
		$form->setAction($base_url . "/login/login");

		$form->addElement('text', 'username', array(
            'label'    => 'Name:',
		    'required' => true,
		    'filters'  => array('StringToLower','StringTrim'),
		));

		$form->addElement('password', 'password', array(
            'label'    => 'Password:',
		    'required' => true,
		    'filters'  => array('StringTrim'),
		));

		// Add the submit button
		$form->addElement('submit', 'submit', array(
            'ignore'   => true,
            'label'    => 'Submit',
		));
		return $form;
	}

	public function indexAction()
	{
		$this->logger->log($this, Zend_Log::DEBUG);
		$this->view->form = $this->getForm();
		$this->render('form');
	}


	public function loginAction()
	{
		if (!$this->getRequest()->isPost()) {
			return $this->_forward('index');
		}
		$form = $this->getForm();
		if (!$form->isValid($_POST)) {
			// Failed validation; redisplay form
			$this->view->form = $form;
			return $this->render('form');
		}

		$resource = $this->bootstrap->getPluginResource('db');
		$dbAdapter = $resource->getDbAdapter();

		$authAdapter = new Zend_Auth_Adapter_DbTable(
		$dbAdapter,
		    'dict_user',
		    'username',
		    'password'
		    );

		    $values = $form->getValues();
		    $authAdapter
		    ->setIdentity($values["username"])
		    ->setCredential($values["password"]);

		    $authResult = Zend_Auth::getInstance()->authenticate($authAdapter);

		    if (Zend_Auth::getInstance()->hasIdentity()) {
		    	// Identity exists; get it
		    	$identity = Zend_Auth::getInstance()->getIdentity();
		    }


		    if ($authResult->isValid()) {
		    	$this->logger->log(print_r($authResult->getMessages(), true), Zend_Log::WARN);
		    	$userTable = new Default_Model_DbTable_UserTable();
		    	$user =  $userTable->findByName($identity)->fetchObject();
		    	$_SESSION["user_info"] = array("user_id" => $user->id, "username" => $user->username);
		    	$this->_redirect("/index");
		    } else {
		    	$this->view->form = $form;
		    	$this->logger->log(print_r($authResult, true), Zend_Log::INFO);
		    	switch ($authResult->getCode()) {

		    		case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
		    			$form->addError("user [" . $values["username"] . "] not exist");
		    			break;

		    		case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
		    			$form->addError("password is wrong");
		    			break;

		    		case Zend_Auth_Result::SUCCESS:
		    			break;

		    		default:
		    			break;
		    	}
		    	return $this->render('form');
		    }
		    //$this->logger->log(print_r($authResult, true), Zend_Log::ALERT);
	}
	
	public function logoutAction() {
		if(Zend_Auth::getInstance()->hasIdentity()) {
			Zend_Auth::getInstance()->clearIdentity();
		}
		$this->_redirect("/index");
	}

}

